<template>
  <view class="idcard-container">
    <!-- 顶部提示 -->
    <view class="tips-card">
      <view class="tips-icon">
        <uni-icons type="info-filled" size="20" color="#1890ff"></uni-icons>
      </view>
      <view class="tips-content">
        <text class="tips-title">上传须知</text>
        <text class="tips-text">1. 请分别上传身份证人像面和国徽面</text>
        <text class="tips-text">2. 确保身份证信息清晰完整，无遮挡</text>
        <text class="tips-text">3. 支持JPG、PNG格式，大小不超过5MB</text>
        <text class="tips-text">4. 上传后系统将自动添加水印保护您的隐私</text>
      </view>
    </view>

    <!-- 身份证正面（人像面） -->
    <view class="idcard-section">
      <view class="section-header">
        <text class="section-title">身份证人像面</text>
        <text class="required">*</text>
      </view>
      
      <!-- 识别的信息 - 简化版手动输入 -->
      <view class="info-panel">
        <view class="info-item">
          <text class="info-label">姓名：</text>
          <input 
            class="info-input" 
            v-model="idCardFront.name" 
            placeholder="请输入真实姓名"
            @blur="saveIdCardInfo"
          />
        </view>
        <view class="info-item">
          <text class="info-label">身份证号：</text>
          <input 
            class="info-input" 
            v-model="idCardFront.idNumber" 
            placeholder="请输入18位身份证号"
            maxlength="18"
            @blur="saveIdCardInfo"
          />
        </view>
      </view>
      
      <!-- 图片上传组件 -->
      <image-uploader
        ref="frontUploader"
        :upload-type="'watermark'"
        :upload-text="'点击上传身份证人像面'"
        :upload-hint="'请上传清晰的身份证人像面照片'"
        :initial-image-url="idCardFront.imageUrl"
        @upload-complete="handleFrontImageUploadComplete"
        @upload-error="handleImageUploadError"
      />
    </view>

    <!-- 身份证反面（国徽面） -->
    <view class="idcard-section">
      <view class="section-header">
        <text class="section-title">身份证国徽面</text>
        <text class="required">*</text>
      </view>
      
      <!-- 图片上传组件 -->
      <image-uploader
        ref="backUploader"
        :upload-type="'watermark'"
        :upload-text="'点击上传身份证国徽面'"
        :upload-hint="'请上传清晰的身份证国徽面照片'"
        :initial-image-url="idCardBack.imageUrl"
        @upload-complete="handleBackImageUploadComplete"
        @upload-error="handleImageUploadError"
      />
      
      <!-- 国徽面已上传提示 -->
      <view v-if="idCardBack.imageUrl" class="info-panel">
        <view class="upload-success">
          <uni-icons type="checkmarkempty" size="20" color="#52c41a"></uni-icons>
          <text class="success-text">国徽面已上传</text>
        </view>
      </view>
    </view>

    <!-- 认证状态 -->
    <!-- <view v-if="certificationStatus" class="status-section">
      <view class="status-header">
        <text class="status-title">认证状态</text>
        <view :class="['status-badge', getStatusClass()]">
          <uni-icons :type="getStatusIcon()" size="14" :color="getStatusColor()"></uni-icons>
          <text class="status-text">{{ getStatusText() }}</text>
        </view>
      </view>
      <view v-if="certificationStatus === '2'" class="reject-reason">
        <text class="reason-label">驳回原因：</text>
        <text class="reason-text">{{ rejectReason }}</text>
      </view>
    </view> -->

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button 
        v-if="idCardFront.imageUrl && idCardBack.imageUrl" 
        class="btn-reupload" 
        @click="reupload"
      >
        重新上传
      </button>
      <button 
        v-if="canSubmit" 
        class="btn-submit" 
        @click="submitForReview"
        :disabled="submitting"
      >
        {{ submitting ? '提交中...' : '提交认证' }}
      </button>
    </view>

    <!-- 隐私说明 -->
    <view class="privacy-notice">
      <uni-icons type="locked" size="16" color="#999"></uni-icons>
      <text class="privacy-text">您的身份信息将被严格保密，仅用于实名认证</text>
    </view>
  </view>
</template>

<script>
import config from '@/config';
import ImageUploader from '@/components/image-uploader.vue';
const baseUrl = config.baseUrl;

export default {
  components: {
    ImageUploader
  },
  
  data() {
    return {
      idCardFront: {
        imageUrl: '',
        name: '',
        idNumber: '',
        gender: '',
        nation: '',
        birth: '',
        address: ''
      },
      idCardBack: {
        imageUrl: '',
        validDate: '',
        issueAuthority: ''
      },
      certificationStatus: '', // 0-待审核, 1-已认证, 2-审核失败
      rejectReason: '',
      submitting: false
    }
  },
  
  computed: {
    canSubmit() {
      return this.idCardFront.imageUrl && 
             this.idCardBack.imageUrl && 
             this.certificationStatus !== '1' &&
             this.certificationStatus !== '0'
    }
  },
  
  onLoad() {
    this.loadIdCardInfo()
  },
  
  methods: {
    // 加载身份证信息
    async loadIdCardInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        const res = await this.$http.get('/system/merchant/idcard')
        if (res.code === 200 && res.data) {
          this.idCardFront = res.data.front || this.idCardFront
          this.idCardBack = res.data.back || this.idCardBack
          this.certificationStatus = res.data.status
          this.rejectReason = res.data.rejectReason
        }
      } catch (error) {
        console.error('加载身份证信息失败:', error)
      } finally {
        uni.hideLoading()
      }
    },
    
    // 人像面上传完成处理
    handleFrontImageUploadComplete(imageUrl) {
      this.idCardFront.imageUrl = imageUrl;
      
      // 如果图片被删除（空字符串），清空相关信息
      if (!imageUrl) {
        this.idCardFront.name = '';
        this.idCardFront.idNumber = '';
      }
      // 保存身份证信息
      this.saveIdCardInfo();
    },
    
    // 国徽面上传完成处理
    handleBackImageUploadComplete(imageUrl) {
      this.idCardBack.imageUrl = imageUrl;
      
      // 如果图片被删除（空字符串），清空相关信息
      if (!imageUrl) {
        this.idCardBack.validDate = '';
        this.idCardBack.issueAuthority = '';
      }
      // 保存身份证信息
      this.saveIdCardInfo();
    },
    
    // 图片上传错误处理
    handleImageUploadError(error) {
      console.error('图片上传失败:', error);
      // 可以根据错误类型进行不同的提示
      if (error.message && error.message.includes('大小')) {
        uni.showToast({
          title: error.message,
          icon: 'none',
        });
      } else {
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none',
        });
      }
    },
    
    // 保存身份证信息
    async saveIdCardInfo() {
      try {
        const res = await this.$http.post('/system/merchant/idcard', {
          front: this.idCardFront,
          back: this.idCardBack
        })
        
        if (res.code === 200) {
          console.log('保存成功')
        }
      } catch (error) {
        console.error('保存身份证信息失败:', error)
      }
    },
    
    // 重新上传
    reupload() {
      uni.showModal({
        title: '确认重新上传',
        content: '重新上传将清除当前的身份证信息，是否继续？',
        success: (res) => {
          if (res.confirm) {
            this.idCardFront = {
              imageUrl: '',
              name: '',
              idNumber: '',
              gender: '',
              nation: '',
              birth: '',
              address: ''
            }
            this.idCardBack = {
              imageUrl: '',
              validDate: '',
              issueAuthority: ''
            }
            this.certificationStatus = ''
            this.rejectReason = ''
          }
        }
      })
    },
    
    // 提交认证
    async submitForReview() {
      if (!this.idCardFront.imageUrl || !this.idCardBack.imageUrl) {
        uni.showToast({
          title: '请上传身份证正反面',
          icon: 'none'
        })
        return
      }
      
      uni.showModal({
        title: '确认提交',
        content: '确定要提交身份证进行实名认证吗？',
        success: async (res) => {
          if (res.confirm) {
            this.submitting = true
            try {
              const response = await this.$http.post('/system/merchant/idcard/submit', {
                front: this.idCardFront,
                back: this.idCardBack
              })
              
              if (response.code === 200) {
                uni.showToast({
                  title: '提交成功',
                  icon: 'success'
                })
                this.certificationStatus = '0' // 待审核
                
                // 返回上一页
                setTimeout(() => {
                  uni.navigateBack()
                }, 1500)
              } else {
                uni.showToast({
                  title: response.msg || '提交失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('提交失败:', error)
              uni.showToast({
                title: '提交失败',
                icon: 'none'
              })
            } finally {
              this.submitting = false
            }
          }
        }
      })
    },
    
    // 格式化身份证号（隐藏中间部分）
    formatIdNumber(idNumber) {
      if (!idNumber || idNumber.length < 18) return idNumber
      return idNumber.substring(0, 6) + '********' + idNumber.substring(14)
    },
    
    // 获取状态样式
    getStatusClass() {
      const statusMap = {
        '0': 'warning',
        '1': 'success',
        '2': 'error'
      }
      return statusMap[this.certificationStatus] || ''
    },
    
    // 获取状态图标
    getStatusIcon() {
      const iconMap = {
        '0': 'info',
        '1': 'checkmarkempty',
        '2': 'close'
      }
      return iconMap[this.certificationStatus] || 'info'
    },
    
    // 获取状态颜色
    getStatusColor() {
      const colorMap = {
        '0': '#faad14',
        '1': '#52c41a',
        '2': '#ff4d4f'
      }
      return colorMap[this.certificationStatus] || '#999'
    },
    
    // 获取状态文本
    getStatusText() {
      const textMap = {
        '0': '待审核',
        '1': '已认证',
        '2': '审核失败'
      }
      return textMap[this.certificationStatus] || '未认证'
    }
  }
}
</script>

<style scoped>
.idcard-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

/* 提示卡片 */
.tips-card {
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: flex-start;
}

.tips-icon {
  margin-right: 16rpx;
  margin-top: 4rpx;
}

.tips-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.tips-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #1565C0;
  margin-bottom: 12rpx;
}

.tips-text {
  font-size: 26rpx;
  color: #1976D2;
  line-height: 1.6;
  margin-bottom: 8rpx;
}

/* 身份证区域 */
.idcard-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.required {
  color: #ff4d4f;
  margin-left: 8rpx;
}



/* 信息面板 */
.info-panel {
  margin-top: 20rpx;
  padding: 24rpx;
  background: linear-gradient(135deg, #f6f8fb 0%, #ffffff 100%);
  border-radius: 12rpx;
  border: 1rpx solid #e8ecf0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 12rpx 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 140rpx;
  font-size: 26rpx;
  color: #666;
  margin-right: 16rpx;
  text-align: right;
}

.info-value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

.info-input {
  flex: 1;
  height: 72rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  background: #ffffff;
  border: 2rpx solid #e1e8ee;
  border-radius: 8rpx;
  transition: all 0.3s;
}

.info-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
}

.upload-success {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
}

.success-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #52c41a;
}

/* 状态区域 */
.status-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.status-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.status-badge.success {
  background: #f6ffed;
  border: 1rpx solid #b7eb8f;
}

.status-badge.warning {
  background: #fffbe6;
  border: 1rpx solid #ffe58f;
}

.status-badge.error {
  background: #fff2f0;
  border: 1rpx solid #ffccc7;
}

.status-text {
  font-size: 24rpx;
  margin-left: 8rpx;
}

.reject-reason {
  margin-top: 20rpx;
  padding: 16rpx;
  background: #fff2f0;
  border-radius: 8rpx;
  border-left: 4rpx solid #ff4d4f;
}

.reason-label {
  font-size: 26rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.reason-text {
  font-size: 26rpx;
  color: #666;
  margin-left: 12rpx;
}

/* 操作按钮 */
.action-buttons {
  margin: 20rpx;
  display: flex;
  gap: 30rpx;  /* 增加按钮间距 */
}

.btn-reupload, .btn-submit {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: bold;
  border: none;
}

.btn-reupload {
  background: #fff;
  color: #1890ff;
  border: 2rpx solid #1890ff;
}

.btn-submit {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
}

.btn-submit[disabled] {
  opacity: 0.6;
}

/* 隐私说明 */
.privacy-notice {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  margin-top: 20rpx;
}

.privacy-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 12rpx;
}
</style>